package com.zgroup.services

import com.zgroup.common.CheckUtils
import com.zgroup.domain.BusinessInfo
import com.zgroup.domain.Company
import com.zgroup.domain.InfoRelease
import com.zgroup.domain.User

class UserService extends DynamicService {

  boolean transactional = true

  def championByNum() {
    String query = "select b.user from Bid as b where b.status='10' and b.expired='0' group by b.user order by count(*) desc"
    User.executeQuery(query, [max: 1])?.getAt(0)
  }

  def bidUser(date) {
    String query = "from User u where exists(select 1 from Bid b where b.user=u and b.dateCreated like '" + date + "%')"
    paginateList(query, [], [:], User.class)
  }

  def countPublishedInfo(pUser) {
    String query = "select count(distinct i) from Estate as e, InfoRelease as i,Bid as b where i.publisher=? and i.publisher=b.user and b.status='10' and b.expired='0' and e in elements(i.estates) and b in (e.vipBid,e.firstBid,e.secondBid,e.thirdBid) "
    User.executeQuery(query, [pUser], [max: 1])?.getAt(0)
  }

  def randomPublishedInfo(pUser, pSize) {
    String query = "select distinct i from InfoRelease as i,Estate as e ,Bid as b where i.publisher=? and i.publisher=b.user and b.status='10' and e in elements(i.estates) and b in (e.vipBid,e.firstBid,e.secondBid,e.thirdBid) order by rand()"
    InfoRelease.executeQuery(query, [pUser], [max: pSize])
  }

  def countByEstate(pEstate) {
    String query = "select count(*) as c from User as u where u.homeEstate=?  or u.companyEstate=? "
    return User.executeQuery(query, [pEstate, pEstate]).getAt(0)
  }

  def saveBusinessInfo(params) {
    def domain;
    if (CheckUtils.isEmpty(params.id)) {
      domain = new BusinessInfo()
      domain.user = User.get(params.userid);
    } else {
      domain = BusinessInfo.get(params.id);
    }
    domain.properties = params
    if (domain.save()) {
      return true
    } else {
      domain.errors.each {
        println it
      }
      return false
    }
  }

  def saveCompany(params) {
    def domain;
    if (CheckUtils.isEmpty(params.id)) {
      domain = new Company();
    } else {
      domain = Company.get(params.id);
    }
    domain.properties = params
    def user = User.get(params.createUser.id);
    user.company = domain;
    if (domain.save() && user.save()) {
      return true
    } else {
      domain.errors.each {
        println it
      }
      return false
    }
  }
}
